package com.geekstudy.week11;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

@RunWith(BlockJUnit4ClassRunner.class)
public class JedisPubSubVerify {

    @Test
    public void testJedisPubSub() {
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        String channel = "DemoPubSub";

        // 端口号错误 redis.clients.jedis.exceptions.JedisConnectionException: Failed to create socket

        for(int size = 1; size <= 2; size++) {
            String message = "Message 202109 v" + size;
            jedis.publish(channel, message);
            System.out.println(" publish 2021 message" + size + " ");
        }

        JedisPubSub demoPubSub = new JedisPubSubDemo();
        // 使用新线程 订阅Redis publish 消息
        Thread thread = new Thread(){

            @Override
            public void run() {
                jedis.subscribe(demoPubSub, channel);
                while(true) {
                    demoPubSub.subscribe(channel);
                }

            }
        };
        thread.start();


        for(int size = 1; size <= 3; size++ ) {
            String message = "Message Demo v" + size;
            jedis.publish(channel, message);
            System.out.println(" publish Demo message" + size + " ");
        }

        for(int size = 1; size <= 3; size++) {
            String message = "OnMessage v" + size + " ";
            demoPubSub.onMessage(channel, message);
        }


        try {
            Thread.sleep(1000 * 10);
        } catch(Exception e) {
            e.printStackTrace();
        }






    }
}
